package com.opgea.crm.services.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.opgea.crm.common.vo.RoleVo;
import com.opgea.crm.domain.entities.security.Group;
import com.opgea.crm.domain.entities.security.Role;
import com.opgea.crm.domain.modal.QualifierModel;
import com.opgea.crm.repository.security.GroupRepository;
import com.opgea.crm.repository.security.RoleRepository;
@Service
public class RoleServiceImpl implements RoleService{

	@Autowired
	RoleRepository roleRepository;
	@Autowired
	GroupRepository groupRepository;
	
	public void create(Role role) {
		roleRepository.create(role);
	}

	public Role find(Long id) {
		return roleRepository.find(id);
	}

	public List<Role> findAll() {
		return roleRepository.findAll();
	}
	
	public List<QualifierModel> findAllRoleNames(){
		List<Role> roles = roleRepository.findAll();
		List<QualifierModel> roleList = new ArrayList<QualifierModel>();
		for(Role role : roles){
			roleList.add(new QualifierModel(role.getId(), role.getName()));
		}
		return roleList;
	}

	public List<RoleVo> findAllRoles() {
		List<Role> roles = roleRepository.findAll();
		List<RoleVo> roleList = new ArrayList<RoleVo>();
		for(Role role : roles){
			roleList.add(new RoleVo(role.getId(), role.getName()));
		}
		return roleList;
	}
	
	public List<RoleVo> findAllByName(String name) {
		List<Role> roles = roleRepository.findAllByName(name);
		List<RoleVo> roleList = new ArrayList<RoleVo>();
		for(Role role : roles){
			roleList.add(new RoleVo(role.getId(), role.getName()));
		}
		return roleList;
	}	
	
	public List<RoleVo> findAllRolesByGroup(Long groupId, boolean onlyAssigned) {
		Group group = groupRepository.find(groupId);
		List<Role> groupRoles = group.getRoles();
		List<Role> roles = roleRepository.findAll();
		
		List<RoleVo> roleList = new ArrayList<RoleVo>();
		for(Role role : roles){
			RoleVo roleVo = null;
			if(groupRoles.contains(role)){
				roleVo = new RoleVo(role.getId(), role.getName(), true);
				System.out.println(roleVo);
				roleList.add(roleVo);
			}else{
				if(onlyAssigned == false){
					roleVo = new  RoleVo(role.getId(), role.getName(), false);
					roleList.add(roleVo);
				}
			}
			
		}
		return roleList;
	}	
	
	public void update(Role role) {
		roleRepository.update(role);
	}

	public void remove(Long id) {
		roleRepository.remove(id);
	}
}
